import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import { API, API_PREFIX, SERVER_BASE } from "@/config";
 import FormData from 'form-data'

export default NextAuth({
  session: {
    strategy: `jwt`
  },
  providers: [
    CredentialsProvider({
      // The name to display on the sign in form (e.g. "Sign in with...")
      name: "Credentials",
      credentials: {
        account: {label: "用户名", type: "text", placeholder: "请输入用户名"},
        password: {label: "密码", type: "password", placeholder: "请输入密码"}
      },
      async authorize(credentials, req) {
        // Add logic here to look up the user from the credentials supplied
        const {token,position} = credentials;
        let user

        try {

          let resp = await fetch(`${SERVER_BASE}${API_PREFIX}${API.user.userinfo}`, {
          // let resp = await fetch(`https://car.varwey.com/exam1125api${API.user.userinfo}`, {
            headers: {
              Authorization: `Bearer ${token}`
            }
          });
          resp = await resp.json();
          const formdata = new FormData()
          formdata.append('category','Login')
          formdata.append('position', position || '')
          fetch(`${SERVER_BASE}${API_PREFIX}${API.user.userUserAccess}`,{method:'POST',body: formdata,headers: {Authorization: `Bearer ${token}`},}).then((res) => {
          }).catch(error => {
            console.log(error,'error')
          })
          console.log(`resp`, resp)

          if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
            return null
          }
          console.log(resp)
          user = resp.data;
        } catch (e) {
          console.log(`e`, e)
        }

        if (user) {
          // Any object returned will be saved in `user` property of the JWT
          return user
        } else {
          // If you return null then an error will be displayed advising the user to check their details.
          return null

          // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
        }
      }
    })
  ],
  callbacks: {
    jwt: ({token, user, account, profile, isNewUser}) => {
      Object.assign(token, user);
      console.log('jwt')
      return token
    },
    session: ({session, token, user}) => {
      console.log(session,'session')
      Object.assign(session.user, token)

      return session
    },
  },
  secret: `68`,
  jwt: {
    maxAge: 60 * 60 * 24 * 7,
    secret: `68`,
    encryption: true
  },
  pages: {
    signIn: `/`
  }
})